package com.lxk.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.lxk.config.UrlConfig;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QRCodeGenerator {

    //CFG 二维码文件夹
    private static final String QR_CODE_PATH = "qrcode/";

    /**
     * 生成二维码
     * @param text
     * @param width
     * @param height
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static String generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        //生成 filePath与 url
        String fileName = CodeUtil.generateUUIDCode() + ".png";
        String filePath = UrlConfig.getStaticPath() + QR_CODE_PATH + fileName;
        String fileUrl = UrlConfig.SERVER_URL + QR_CODE_PATH + fileName;
        //生成二维码
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        return fileUrl;
    }

    /**
     * 二维码链接是否有效
     * @param urlString
     * @return
     */
    public static boolean isQrcodeExist(String urlString) {
        int idx = urlString.lastIndexOf("/");
        String fileName = urlString.substring(idx + 1);
        String filePath = UrlConfig.getStaticPath() + QR_CODE_PATH + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

}
